package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;

import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.AdvertisementRecordActivity;
import com.srwl.mytx.activity.ChangeActivity;
import com.srwl.mytx.activity.DonationRecordActivity;
import com.srwl.mytx.activity.FollowFansRecordActivity;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.activity.ProfileActivity;
import com.srwl.mytx.activity.SettingActivity;
import com.srwl.mytx.activity.TaskRecordActivity_v1;
import com.srwl.mytx.activity.TopicRecordActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.HashMap;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by dahai2070 on 2016/10/10 0010.
 */
public class ProfileFragment extends BaseFragment implements View.OnClickListener {
    private BroadcastReceiver receiver;
    private Context appContext;
    private ImageView img_icon;
    private TextView tv_userName;
    private User user;
    private TextView tv_fans_num;
    private TextView tv_follow_num;
    private ImageView iv_userSetting;
    private View userInfo;
    private MaterialSmoothRefreshLayout refreshLayout;
    private String TAG = "ProfileFragment";
    private LocalBroadcastManager broadcastManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        // showGuide();
        initBroadCast();
    }


    protected void initView() {

        img_icon = getView().findViewById(R.id.img_icon);
        tv_userName = getView().findViewById(R.id.tv_user_nick);
        tv_fans_num = getView().findViewById(R.id.tv_fans_num);
        tv_follow_num = getView().findViewById(R.id.tv_follow_num);
        iv_userSetting = getView().findViewById(R.id.iv_user_setting);
        refreshLayout = getView().findViewById(R.id.swipe_refresh_Layout);
        showUserInfo();
        if (!isTempUser()) {
            checkFollow();
        }
        iv_userSetting.setOnClickListener(this);
        userInfo = getView().findViewById(R.id.rl_user_info);
        userInfo.setOnClickListener(this);
        getView().findViewById(R.id.rl_donation_record).setOnClickListener(this);
        getView().findViewById(R.id.rl_topic_record).setOnClickListener(this);
        getView().findViewById(R.id.rl_wallet).setOnClickListener(this);
        getView().findViewById(R.id.rl_setting).setOnClickListener(this);
        getView().findViewById(R.id.rl_advertisement_record).setOnClickListener(this);
        getView().findViewById(R.id.rl_fans).setOnClickListener(this);
        getView().findViewById(R.id.rl_follow).setOnClickListener(this);
        getView().findViewById(R.id.rl_task).setOnClickListener(this);


        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                if (isTempUser()) {
                    refreshLayout.refreshComplete();
                } else {
                    checkFollow();
                }
            }

            @Override
            public void onLoadingMore() {

            }
        });
    }

    private void showUserInfo() {
        user = UserProfileManager.getInstance().getLoginUserInfo();
        if (user.getUsername() != null) {
            tv_userName.setText(user.getUsername());
        } else if (user.getNick() != null) {
            tv_userName.setText(user.getNick());
        }

        //Glide.with(this).load(user.getAvatar()).into(img_icon);
        GlideLoadUtils.glideLoad(getActivity(), user.getAvatar(), img_icon);

    }

    /**
     * 广播接收者
     */
    private void initBroadCast() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context1, Intent intent) {
                showUserInfo();

            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_HEAD_LOAD);
        broadcastManager = LocalBroadcastManager.getInstance(appContext);
        broadcastManager.registerReceiver(receiver, intentFilter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            showUserInfo();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_fans:
                if (isTempUser()) {
                    LoginActivity.startActivity(getActivity(), "查询粉丝列表需要先登录");
                } else {
                    startActivity(new Intent(getActivity(), FollowFansRecordActivity.class).putExtra(Constant.EXTRA_INFO_IS_SHOW_FANS, true).putExtra("uid", user.getuId()));
                }
                break;
            case R.id.rl_follow:
                // 2019/4/7 点击跳转关注列表
                if (isTempUser()) {
                    LoginActivity.startActivity(getActivity(), "查询关注列表需要先登录");

                } else {
                    startActivity(new Intent(getActivity(), FollowFansRecordActivity.class).putExtra("uid", user.getuId()));
                }

                break;
            case R.id.rl_user_info:
                getActivity().startActivity(new Intent(getActivity(), UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, user));
                break;
            case R.id.iv_user_setting:
//                String phoneNumber = UserProfileManager.getInstance().getUserPhoneNumber();
//                if (TextUtils.isEmpty(phoneNumber)) {
//                    ConfirmDialog confirmDialog = new ConfirmDialog(getContext(), "提示", "绑定手机号才能设置个人信息，去绑定？", true);
//                    confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                        @Override
//                        public void confirm() {
//                            startActivityForResult(new Intent(getActivity(), UpdateUserInfoActivity.class),
//                                    0);
//                        }
//                    });
//                    confirmDialog.show();
//                } else {
//                    startActivityForResult(new Intent(getActivity(), ProfileActivity.class), 0);
//                }
                if (isTempUser()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("EXTRA_CONTENT", "个人信息设置需要先登录"));
                } else {
                    startActivityForResult(new Intent(getActivity(), ProfileActivity.class), 0);
                }
                break;
            case R.id.rl_donation_record:
                if (isTempUser()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("EXTRA_CONTENT", "查询捐赠记录需要先登录"));
                } else {
                    startActivity(new Intent(getActivity(), DonationRecordActivity.class));
                }
                break;
            case R.id.rl_topic_record:
                if (isTempUser()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("EXTRA_CONTENT", "查看个人动态发布信息要先登录"));
                } else {
                    startActivity(new Intent(getActivity(), TopicRecordActivity.class));
                }
                break;
            case R.id.rl_wallet:
                if (isTempUser()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("EXTRA_CONTENT", "查看钱包需要先登录"));
                } else {
                    startActivity(new Intent(getActivity(), ChangeActivity.class));
                }
                break;
            case R.id.rl_setting:
                if (isTempUser()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("EXTRA_CONTENT", "使用基础设置需要先登录"));
                } else {
                    startActivity(new Intent(getActivity(), SettingActivity.class));
                }
                break;
            case R.id.rl_advertisement_record:
                if (isTempUser()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("EXTRA_CONTENT", "查看广告投放记录需要先登录"));
                } else {
                    startActivity(new Intent(getActivity(), AdvertisementRecordActivity.class));
                }
                break;
            case R.id.rl_task:
                if (isTempUser()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("EXTRA_CONTENT", "查看悬赏任务需要先登录"));
                } else {
                    startActivity(new Intent(getActivity(), TaskRecordActivity_v1.class));
                }
                //   startActivity(new Intent(getActivity(), TaskRecordActivity.class));
                break;
        }
    }


    /**
     * 查询关注粉丝数量
     *
     * @param
     */
    private void checkFollow() {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (refreshLayout != null) refreshLayout.refreshComplete();
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        String uid = user.getuId();
        Map<String, String> object = new HashMap<>();
        object.put("targetUid", uid);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .checkAttention(object).enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                refreshLayout.refreshComplete();
                CommonResult result = response.body();
                if (!response.isSuccessful() || result == null) {
                    Log.e(TAG, "onResponse: " + response.message());
//                    ConfirmDialog dialog = new ConfirmDialog(getActivity(), "提示", "系统繁忙");
//                    dialog.show();
                    return;
                }
                JSONObject data = (JSONObject) response.body().getData();

                Long fansNum = data.getLong("fansNum");
                Long followNum = data.getLong("attentionSize");
                tv_fans_num.setText(Utils.numberFormat(fansNum));
                tv_follow_num.setText(Utils.numberFormat(followNum));


            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                refreshLayout.refreshComplete();
                Log.e(TAG, "onFailure: " + t.getMessage());
//                ConfirmDialog dialog = new ConfirmDialog(getActivity(), "提示", "系统繁忙");
//                dialog.show();

            }
        });


    }


//    private void showGuide() {
//        Animation enterAnimation = new AlphaAnimation(0f, 1f);
//        enterAnimation.setDuration(800);
//        enterAnimation.setFillAfter(true);
//
//        Animation exitAnimation = new AlphaAnimation(1f, 0f);
//        exitAnimation.setDuration(600);
//        exitAnimation.setFillAfter(true);
//
//        //新增多页模式，即一个引导层显示多页引导内容
//        NewbieGuide.with(this)
//                .setLabel("profileFragment")//设置引导层标示区分不同引导层，必传！否则报错
////                .anchor(anchor)
//                .setOnGuideChangedListener(new OnGuideChangedListener() {
//                    @Override
//                    public void onShowed(Controller controller) {
//                        Log.e(TAG, "NewbieGuide onShowed: ");
//                        //引导层显示
//                    }
//
//                    @Override
//                    public void onRemoved(Controller controller) {
//                        Log.e(TAG, "NewbieGuide  onRemoved: ");
//                        //引导层消失（多页切换不会触发）
//                    }
//                })
//                .setOnPageChangedListener(new OnPageChangedListener() {
//
//                    @Override
//                    public void onPageChanged(int page) {
//                        //引导页切换，page为当前页位置，从0开始
//                        // Toast.makeText(getActivity(), "引导页切换：" + page, Toast.LENGTH_SHORT).show();
//                    }
//                })
//                // .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
//                .addGuidePage(//添加一页引导页
//                        GuidePage.newInstance()//创建一个实例
//                                .addHighLight(userInfo, HighLight.Shape.ROUND_RECTANGLE, 5)//添加高亮的view
//                                .setLayoutRes(R.layout.view_guide_to_user_profile)//设置引导页布局
//                                .setEnterAnimation(enterAnimation)//进入动画
//                                .setExitAnimation(exitAnimation)//退出动画
//                )
//                .addGuidePage(GuidePage.newInstance()
//                        .addHighLight(iv_userSetting, HighLight.Shape.CIRCLE, 30)
//                        .setLayoutRes(R.layout.view_guide_to_set_profile, R.id.iv)//引导页布局，点击跳转下一页或者消失引导层的控件id
//                        .setEverywhereCancelable(false)//是否点击任意地方跳转下一页或者消失引导层，默认true
//                        //.setBackgroundColor(getResources().getColor(R.color.transparent_black))//设置背景色，建议使用有透明度的颜色
//                        .setEnterAnimation(enterAnimation)//进入动画
//                        .setExitAnimation(exitAnimation)//退出动画
//                ).show();//显示引导层(至少需要一页引导页才能显示)
//    }


    /**
     * 判断是否是游客
     *
     * @return
     */
    private boolean isTempUser() {
        return Utils.isTempUser(user);

    }

    public void refresh() {
        showUserInfo();
        if (!isTempUser()) {
            checkFollow();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(receiver);
    }
}

